import React, { Component, Fragment } from 'react'
import {createPortal} from 'react-dom';
import Styles from './index.less'
class Portal extends Component {
  constructor(props) {
    super(props)
    this.node = document.createElement('div')
    document.body.appendChild(this.node)
    this.closeModal = this.closeModal.bind(this)
  }
  closeModal() {
    this.props.onCancel()
  }
  stopPropagation(e) {
    e.stopPropagation()
  }
  render() {
    return createPortal(
      [
        <div className={Styles.mask} key="mask"></div>,
        <div className={Styles.wrap} key="main" onClick={this.closeModal}>
          <div className={Styles.dialog} onClick={this.stopPropagation}>
            {this.props.children}
          </div>
        </div>
      ],
      this.node
    )
  }
  componentDidMount() {
    let body = document.body
    body.style.overflow = 'hidden'
  }
  componentWillUnmount() {
    let body = document.body
    body.style.overflow = 'visible'
    body.removeChild(this.node)
  }
}
export default function Modal(props) {
  return props.visible ? <Portal onCancel={props.onCancel} children={props.children}/> : null
}
